const express = require('express');
const contentCategoryService = require('../service/ContentCategoryService')
const ResultUtil = require('../utils/ResultUtil')

/**
 * 业务控制层： 查询文章分类列表
 * @param {*} req 
 * @param {*} res 
 */
const categoryList = async (req, res) => {
  const category = req.query
  let categoryList = null
  try {
    categoryList = await contentCategoryService.selecCategoryList(category)
    res.send(ResultUtil.success(200).add(categoryList))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 根据文章分类id查询文章分类信息
 * @param {*} req 
 * @param {*} res 
 */
const selectCategoryById = async (req, res) => {
  const { id } = req.params
  console.log(req.params)
  try {
    const category = await contentCategoryService.selectCategoryById(id)
    res.send(ResultUtil.success(200, category))
  } catch (error) {
    res.send(ResultUtil.error(500, error.message))
  }
}

/**
 * 业务控制层： 添加文章分类
 * @param {*} req 
 * @param {*} res 
 */
const addCategory = async (req, res) => {
  const category = req.body
  category.createdAt = new Date()
  console.log(category)
  try {
    await contentCategoryService.addCategory(category)
    res.send(ResultUtil.success(201, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 更新文章分类
 * @param {*} req 
 * @param {*} res 
 */
const updateCategory = async (req, res) => {
  const category = req.body
  category.updatedAt = new Date()
  try {
    await contentCategoryService.updateCategory(category)
    res.send(ResultUtil.success(208, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 删除文章分类
 * @param {*} req 
 * @param {*} res 
 */
const deleteCategory = async (req, res) => {
  const { id } = req.body
  console.log(id)
  try {
    await contentCategoryService.deleteCategory(id)
    res.send(ResultUtil.success(204, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

module.exports = {
  categoryList,
  addCategory,
  updateCategory,
  deleteCategory,
  selectCategoryById
}